<script setup lang="ts">
	import { ref, reactive, unref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { route } from '@/uni_modules/uview-plus'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { shopEdit, storeDetail } from '@/package_tms/api/Home'

	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	const orderColumns1 = reactive([
		{
			label: '上次金额',
			field: 'last_visit_time'
		},
		{
			label: '欠款金额',
			field: 'last_order_money'
		},
		{
			label: '总下单额',
			field: 'receivables_money'
		}
	])

	const orderColumns2 = reactive([
		{
			label: '欠款单数',
			field: 'order_count'
		},
		{
			label: '总下单数',
			field: 'full_goods'
		},
		{
			label: '账期时间',
			field: 'selfhelp_order_count'
		}
	])

	const navigationColumns = reactive([
		{
			label: '位置校准',
			icon: '/static/icon/icon2.png'
		},
		// {
		// 	label: '退货',
		// 	icon: '/static/icon/icon3.png',
		// 	pagePath: ''
		// 	// pagePath: '/package_saleman/pages/Order/sales_return'
		// },
		// {
		// 	label: '换货',
		// 	icon: '/static/icon/icon4.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '陈列',
		// 	icon: '/static/icon/icon5.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '收款',
		// 	icon: '/static/icon/icon6.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '往来',
		// 	icon: '/static/icon/icon7.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '查账',
		// 	icon: '/static/icon/icon8.png',
		// 	pagePath: ''
		// }
	])
	const fileList1 = ref([])

	const useStoreDetail = () => {
		const storeInfo = ref({})

		const getStoreInfo = async (id : string) => {
			const params = {
				id
			}
			try {
				const res = await storeDetail(params)
				storeInfo.value = res.data
				if (storeInfo.value?.store_img) {
					fileList1.value = storeInfo.value?.store_img.split(",").map((val) => ({
						url: val
					}))
				} else {
					// 如果不存在，则设置 fileList1.value 为一个空数组
					fileList1.value = [];
				}
			} catch (err) {
				console.log(err);
			}
		}

		return {
			storeInfo,
			getStoreInfo
		}
	}

	const { storeInfo, getStoreInfo } = useStoreDetail()

	const store_id = ref('')

	onLoad((options) => {
		const { id } = options as { id : string }
		store_id.value = id
		getStoreInfo(id)
	})

	// 导航
	const openLocation = () => {
		uni.openLocation({
			latitude: Number(unref(storeInfo).lat),
			longitude: Number(unref(storeInfo).lon),
			name: unref(storeInfo).address,
			success: () => {
				console.log('success');
			},
			fail(err) {
				console.log(err)
			}
		})
	}

	// 电话
	const callStore = () => {
		uni.makePhoneCall({
			phoneNumber: unref(storeInfo).phone
		})
	}
	const useUploadImg = () => {
		// const fileList1 = ref<any[]>([])

		// 添加图片
		type UploadImageFile = {
			size : number,
			type : 'image',
			url : string,
			thumb : string
		}
		type UploadImageParams = {
			file : UploadImageFile | UploadImageFile[],
			index : number,
			name : string
		}
		type AddImage = (event : UploadImageParams) => any
		// 新增图片
		const addImage = async (event) => {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = fileList1.value.length;
			lists.map((item) => {
				fileList1.value.push({
					...item,
					status: 'uploading',
					message: '上传中',
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await uploadImage(lists[i].url);
				let item = fileList1.value[fileListLen];
				fileList1.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result,
				});
				fileListLen++;
			}
			xiuImg()
		};
		// 修改图片
		const xiuImg = async () => {
			try {
				const params = {
					id: store_id.value,
					store_img: fileList1.value.map((item) => item.url).join(',')
				}
				const res = await shopEdit(params)
				showNotify({
					type: 'success',
					message: res.msg
				})
				getStoreInfo(store_id.value)
			} catch (err) {
				showNotify({
					type: 'error',
					message: err.msg
				})
			}
		}

		const uploadImage = (url) => {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: `${process.env.VUE_APP_BASE_URL}/mini/driver/upload`,
					filePath: url,
					name: 'file',
					header: {
						'content-type': 'application/json;charset=utf-8',
						'token': uni.getStorageSync('trioToken'),
					},
					success: (res) => {
						const data = JSON.parse(res.data)
						if (data.code !== 200) {
							uni.showToast({
								title: `${data.msg},请重新上传!`,
								icon: 'none'
							})
							return
						}
						setTimeout(() => {
							resolve(data.data.url);
						}, 1000);
					},
				});
			});
		};
		// 删除图片
		const delImage = (event : UploadImageParams) => {
			fileList1.value.splice(event.index, 1)
		}

		return {
			addImage,
			delImage,
			uploadImage
		}
	}

	const { addImage, delImage, uploadImage } = useUploadImg()

	const toPage = () => {
		uni.chooseLocation({
			success: (res) => {
				if (res.errMsg === 'chooseLocation:ok') {
					console.log('位置名称：' + res.name);
					console.log('详细地址：' + res.address);
					console.log('纬度：' + res.latitude);
					console.log('经度：' + res.longitude);
					xiuLat(res.latitude, res.longitude,res.address)
				}
			}
		})
	}
	// 修改经纬度
	const xiuLat = async (lat, lon,address) => {
		try {
			const params = {
				id: store_id.value,
				lat,
				lon,
				address
			}
			const res = await shopEdit(params)
			showNotify({
				type: 'success',
				message: res.msg
			})
			getStoreInfo(store_id.value)
		} catch (err) {
			showNotify({
				type: 'error',
				message: err.msg
			})
		}
	}
	// 修改门店信息
		const toStoreEdit = () => {
			route({
				url: '/package_tms/pages/Store/editStore',
				params: {
					storeInfo: JSON.stringify(storeInfo.value)
				}
			})
		}
</script>
<template>
	<view class="content">
		<up-navbar :title="storeInfo.store_name" placeholder autoBack></up-navbar>
		<view class="store-info">
			<up-upload :fileList="fileList1" @afterRead="addImage" @delete="delImage" multiple :maxCount="1"
				:previewFullImage="true"></up-upload>
			<!-- <up-avatar :src="storeInfo.img_url" size="200rpx" shape="square"></up-avatar> -->
			<view class="info">
				<view class="line">
					<view>
						<text class="line-name">{{storeInfo.store_name}}</text>
						<text style="font-size: 24rpx;
font-weight: 500;color: rgba(156, 154, 161, 1);">{{storeInfo.last_date}}</text>
					</view>
					<!-- <view><up-button @click="toStoreEdit" type="primary"
							size="mini">修改门店信息</up-button></view> -->
				</view>
				<view class="address" style="margin-top: 30rpx;">
					<text>店主：</text>
					<text style="color: rgba(45, 45, 46, 1);">{{storeInfo.contacts}}</text>
				</view>
				<view class="address" style="margin-top: 10rpx;">
					<text>电话：</text>
					<text style="color: rgba(45, 45, 46, 1);">{{storeInfo.phone}}</text>
				</view>
				<view class="address">
					<text>地址：</text>
					<text style="color: rgba(45, 45, 46, 1);">{{storeInfo.address}}</text>
				</view>
			</view>
		</view>

		<!-- <view class="order-info">
			<up-grid :border="false">
				<up-grid-item v-for="item in orderColumns1" :key="item.field" :customStyle="{ margin: '20rpx 0' }">
					<text class="label">{{item.label}}</text>
					<text class="value">{{ storeInfo[item.field] || '暂无' }}</text>
				</up-grid-item>
			</up-grid>
			<up-line color="#FFFFFF"></up-line>
			<up-grid :border="false">
				<up-grid-item v-for="item in orderColumns2" :key="item.field" :customStyle="{ margin: '20rpx 0' }">
					<text class="label">{{item.label}}</text>
					<text class="value">{{ storeInfo[item.field] || '暂无' }}</text>
				</up-grid-item>
			</up-grid>
		</view> -->
		<view style="margin-top: 100rpx;">
			<view style="font-size: 16px;font-weight: 700;color: rgba(2, 14, 36, 1);margin-left: 30rpx;">辅助工具</view>
			<up-grid :border="false" col="5">
				<up-grid-item v-for="item in navigationColumns" :key="item.pagePath" :name="item.pagePath"
					:customStyle="{ margin: '40rpx 0 50rpx 0' }" @click="toPage">
					<up-icon :name="item.icon" :label="item.label" labelPos="bottom" labelSize="28rpx" space="20rpx"
						width="60rpx" height="60rpx">
					</up-icon>
				</up-grid-item>
			</up-grid>
		</view>

		<view class="bottom-area">
			<view class="line">
				<view class="item">
					<up-icon name="/static/icon/icon9.png" label="电话" labelSize="28rpx" space="20rpx" width="44rpx"
						height="44rpx" \ @click="callStore">
					</up-icon>
				</view>
				<view class="item">
					<up-icon name="/static/icon/icon10.png" label="导航" labelSize="28rpx" space="20rpx" width="44rpx"
						height="44rpx" @click="openLocation">
					</up-icon>
				</view>
			</view>
			<!-- <view class="line">
				<up-button class="up-reset-button" color="rgba(55, 131, 252, 1)" size="large" shape="circle" icon="map"
					iconColor="#FFFFFF" text="签到"></up-button>
			</view> -->
		</view>
		<up-notify ref="NotifyRef"></up-notify>
	</view>
</template>

<style scoped lang="scss">
	.content {
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;

		.store-info {
			display: flex;
			align-items: center;
			gap: 20rpx;
			margin-bottom: 40rpx;


			.info {
				width: 100%;
				height: 200rpx;

				.line {
					width: 100%;
					display: flex;
					justify-content: space-between;
					margin-bottom: 10rpx;
					font-size: 24rpx;

					.line-name {
						font-size: 28rpx;
						font-weight: 700;
						color: rgba(35, 35, 36, 1);
						margin-right: 20rpx;
					}

					.header-right {
						display: flex;

						.right-img {
							width: 34rpx;
							height: 34rpx;
							vertical-align: middle;
							margin-right: 20rpx;
						}

						.right-name {
							font-size: 28rpx;
							font-weight: 700;
							color: rgba(55, 131, 252, 1);
						}
					}
				}



				.address {
					font-size: 24rpx;
					color: rgba(156, 154, 161, 1);
				}
			}
		}

		.order-info {
			width: 100%;
			border-radius: 20rpx;
			background: linear-gradient(180deg, rgba(242, 243, 245, 1) 0%, rgba(242, 243, 245, 0) 100%);

			.label {
				font-size: 24rpx;
				color: rgba(156, 154, 161, 1);
				margin: 10rpx 0;
			}

			.value {
				font-size: 28rpx;
			}
		}


		.bottom-area {
			position: fixed;
			bottom: 0;
			left: 0;
			display: flex;
			flex-direction: column;
			gap: 40rpx;
			width: 100%;
			padding: 0 40rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			/* 兼容iOS < 11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS 11.2及以上 */
			box-sizing: border-box;

			.line {
				display: flex;
				justify-content: space-between;

				.item {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 232rpx;
					height: 80rpx;
					border-radius: 40rpx;
					background: rgba(245, 245, 245, 1);
				}
			}
		}

	}
</style>